$(document).ready(function() {
    // 添加新行
    $('#addRow').click(function() {
        const newRow = `
            <tr class="form-row">
                <td>
                    <select name="sku" class="form-control sku-select" required>
                        <option value="">选择SKU</option>
                    </select>
                </td>
                <td><input type="text" name="box_spec" class="form-control" required></td>
                <td><input type="number" name="box_count" class="form-control" min="1" required></td>
                <td><input type="date" name="date" class="form-control" value="${new Date().toISOString().split('T')[0]}"></td>
                <td><textarea name="remark" class="form-control"></textarea></td>
                <td><button type="button" class="btn btn-danger btn-sm remove-row">删除</button></td>
            </tr>
        `;
        const $newRow = $(newRow);
        $('#inboundItems').append($newRow);

        // 动态填充SKU选项
        const $select = $newRow.find('.sku-select');
        skuChoices.forEach(sku => {
            $select.append($('<option>', {
                value: sku,
                text: sku
            }));
        });
    });

    // 删除行
    $(document).on('click', '.remove-row', function() {
        if ($('#inboundItems tr').length > 1) {
            $(this).closest('tr').remove();
        } else {
            alert('至少保留一行记录');
        }
    });

    // 提交表单 - 修改为传统表单提交
    $('#productInboundForm').submit(function(e) {
        e.preventDefault();

        const formData = [];
        let isValid = true;

        $('#inboundItems tr').each(function() {
            const rowData = {
                sku: $(this).find('[name="sku"]').val(),
                box_spec: $(this).find('[name="box_spec"]').val(),
                box_count: $(this).find('[name="box_count"]').val(),
                date: $(this).find('[name="date"]').val(),
                remark: $(this).find('[name="remark"]').val()
            };

            if (!rowData.sku || !rowData.box_spec || !rowData.box_count) {
                isValid = false;
                $(this).find('[name="sku"], [name="box_spec"], [name="box_count"]').addClass('is-invalid');
                return false;
            }

            formData.push(rowData);
        });

        if (!isValid) {
            alert('请填写所有必填字段');
            return;
        }

        // 创建隐藏表单并提交
        const $form = $(this);
        const $hiddenInput = $('<input>', {
            type: 'hidden',
            name: 'form_data',
            value: JSON.stringify(formData)
        });
        $form.append($hiddenInput);

        // 转换为传统表单提交
        $form.off('submit').submit();
    });
});